import { Form, Input, message, Modal } from 'antd';
import { useEffect, useState } from 'react';

import bannerService from '@/api/services/setting/bannerService';

import { BannerType } from './type';
import { UploadPicture } from './upload-picture';

import { ModalProps } from '#/entity';

// export function OrderModal({ title, show, formValue, onOk, onCancel }: ModalProps<Order>) {

export function BannerModal({ title, show, formValue, onOk, onCancel }: ModalProps<BannerType>) {
  const [form] = Form.useForm();
  const [fileData, setFileData] = useState<any[]>([]);
  const [disabled, setDisabled] = useState(false); // 上传按钮是否禁用
  useEffect(() => {
    if (fileData.length > 0) {
      setDisabled(true);
    } else {
      setDisabled(false);
    }
  }, [fileData]);
  const onFinish = (values: any) => {
    const transData = {
      ...values,
    };
    if (formValue.id) {
      // 存在ID则是修改
      bannerService.updateBanner(formValue.id, values).then((res) => {
        if (res > 0) {
          onOk();
          message.success('修改成功');
        }
      });
    } else {
      // 不存在ID则是新增
      bannerService.createBanner(transData).then((res) => {
        if (res > 0) {
          onOk();
          message.success('新增成功');
        }
      });
    }
  };
  const transferPicData = () => {
    return [formValue.file!];
  };
  const onUploadSuccess = (file: number[]) => {
    setFileData(file.map((item) => ({ file: item })));
    form.setFieldsValue({
      file: file[0],
    });
  };
  // ______________________________________________________________
  const num = 10000;
  const effectiveFigure = {
    // 校验二维码宽度是否有效
    pattern: /^\d+$/,
    message: '只能输入数字',
  };
  const effectiveFigureNum = {
    validator: (_, value) => {
      if (value > num) {
        return Promise.reject(new Error(`排序数字不能超过${num}`));
      }
      return Promise.resolve();
    },
  };
  const nameWidth = 64;
  const redirectUrlWidth = 128;
  const modalRender = (dom: React.ReactNode) => (
    <Form
      initialValues={formValue}
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      onFinish={onFinish}
      clearOnDestroy
      layout="horizontal"
      // layout="vertical"
    >
      {dom}
    </Form>
  );

  return (
    <Modal
      width={600}
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnHidden
      modalRender={modalRender}
    >
      <Form.Item
        name="name"
        label="名称"
        rules={[
          { required: true, message: '请输入横幅名称' },
          {
            validator: (_, value) => {
              if (value.length > nameWidth) {
                return Promise.reject(new Error(`名称长度不能超过${nameWidth}`));
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <Input showCount maxLength={nameWidth} />
      </Form.Item>
      <Form.Item
        name="sort"
        label="排序"
        rules={[
          { required: true, message: '请输入横幅排序数字' },
          effectiveFigure,
          effectiveFigureNum,
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="redirectUrl"
        label="跳转链接"
        rules={[
          {
            validator: (_, value) => {
              if (value.length > redirectUrlWidth) {
                return Promise.reject(new Error(`跳转链接长度不能超过${redirectUrlWidth}`));
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <Input showCount maxLength={redirectUrlWidth} />
      </Form.Item>
      <Form.Item
        style={{ textAlign: 'center', marginLeft: '100px' }}
        name="file"
        rules={[
          {
            validator: () => {
              return fileData.length > 0
                ? Promise.resolve()
                : Promise.reject(new Error('请上传图片'));
            },
          },
        ]}
      >
        <UploadPicture
          disabled={disabled}
          portraitList={transferPicData()}
          onUploadSuccess={onUploadSuccess}
        />
      </Form.Item>
    </Modal>
  );
}
